<?php
namespace Library;
include_once "Auto_load.php";
use Library\Common;
use Library\Response;

//	路由导航
class Route
{
	public function __construct($path_info){
		$rePathInfo = Common::rePath($path_info);
		
		$controller = isset($query['c']) ? $query['c'] :"app\\". ucfirst($rePathInfo["pathArray"][1])."\\Controller\\".ucfirst($rePathInfo["pathArray"][2]);
		
		$this->isUrl($path_info,$controller);
		
		$model = "/app/".ucfirst($rePathInfo["pathArray"][1]);
		
		//	判断模块是否存在
		$this->existModel($model);
		//	判断控制器是否存在
		$this->existController($controller);
		
		include_once $rePathInfo["path"];
		
		// 对用户请求URL进行处理
		$query = $_GET;
		
		$action = isset($query['a']) ? $query['a'] :  $rePathInfo["pathArray"][3];
		
		if (class_exists($controller)) {
			
		    if (method_exists($controller, $action)) {
				
		        unset($_GET['c']);
		        unset($_GET['a']);
		        // 实例化用户请求类并调用方法
		        // $res = (new $controller())->$action();
				$controllerClass = (new $controller());
				$res = $controllerClass->$action();
				//	返回类
				new Response($res);
				
		    } else {
				header('Content-language: en');
				header('Content-type:application/json;charset:utf-8');
		        echo json_encode(["code"=>500,"msg"=>'控制器' . $controller . '中不存在方法' . $action],JSON_UNESCAPED_UNICODE);
		    }
		} else {
		    echo $controller."控制器不存在";
		}
	}
	
	public function isUrl($path_info,$ContentType){
		//	判断是否无path访问
		if ( $path_info=="index.php" || $path_info=="" ){
			include_once "app/Index/Controller/Index.php";
			$controllerClass = (new \app\Index\Controller\Index());
			$res = $controllerClass->Index();
			new Response($data,$ContentType="application/json",$code=200,$charset="utf-8");
			exit;
		}
	}
	
	//	验证模块是否存在
	public function existModel($model){
		if (!file_exists($_SERVER["DOCUMENT_ROOT"].$model)){
			header('Content-language: en');
			header('Content-type:application/json;charset:utf-8');
			echo json_encode(["code"=>500,"msg"=>$model."模块不存在!"],JSON_UNESCAPED_UNICODE);
			exit;
		}
	}
	
	//	验证模块是否存在
	public function existController($controller){
		if (!file_exists($controller.".php")){
			header('Content-language: en');
			header('Content-type:application/json;charset:utf-8');
			echo json_encode(["code"=>500,"msg"=>$controller."控制器不存在"],JSON_UNESCAPED_UNICODE);
			exit;
		}
	}
}
?>